/*
 * ./copy 1.txt 2.txt
 * argc = 3
 * argv[0] = "./copy"
 * argv[1] = "1.txt"
 * argv[2] = "2.txt"
 */

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>

int main(int argc, char const *argv[])
{
    int fd_old = -1;
    int fd_new = -1;
    char buf[1024] = {0};
    int len;

    if (argc != 3)
    {
        printf("Usage: %s <old-file> <new-file>\n", argv[0]);
        return -1;
    }

    fd_old = open(argv[1], O_RDONLY);
    if (fd_old < 0)
    {
        perror("open()");
        return -2;
    }

    /*3. 创建新文件*/
    /**
     * O_CREAT 如果要创建文件则需要指定此标志
     * Mode 表示创建文件的权限，只有在 flags 中使用了 O_CREAT 时才有效， 否则忽略。如果没有指定则权限为 --w-------
    */
    fd_new = open(argv[2], O_WRONLY | O_CREAT/* | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH*/);
    if (fd_new < 0)
    {
        perror("open()");
        return -3;
    }

    while ((len = read(fd_old, buf, sizeof(buf))) > 0)
    {
        if(write(fd_new, buf, len) < 0)
        {
            perror("write()");
            return -1;
        }
    }

    /*4. 关闭文件*/
    close(fd_old);
    close(fd_new);

    return 0;
}
